package com.kimu.order_service_consumer.controller;

import java.util.List;

import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kimu.order_service_interface.entity.Order;
import com.kimu.order_service_interface.entity.OrderStatus;
import com.kimu.order_service_interface.service.OrderService;
import com.kimu.user.entity.User;
import com.kimu.user.service.JwtService;
import com.kimu.user.service.UserService;

import jakarta.servlet.http.HttpServletRequest;

@RestController
public class OrderController {

    @DubboReference
    private OrderService orderService;

    @DubboReference
    private UserService userService;

    private JwtService jwtService;

    public OrderController(JwtService jwtService) {
        this.jwtService = jwtService;
    }

    /*
     * 新增一个订单的接口
     */
    @PostMapping(path = "/api/orders")
    public ResponseEntity<Order> createOrder(HttpServletRequest request, @RequestBody Order order) {
        String username = jwtService.getUsername(request);
        if (null == username) {
            return new ResponseEntity<>(HttpStatus.FORBIDDEN);
        }
        User user = userService.findUserByUsername(username);
        if (null == user) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        // 设置订单的用户id为user_id
        order.setUserId(user.getId());
        // 设置订单的状态为未支付（避免前端的攻击）
        order.setStatus(OrderStatus.UNPAID);
        // 创建订单
        int row = orderService.createOrder(order);
        if (row == 0) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        } else {
            return new ResponseEntity<>(order, HttpStatus.CREATED);
        }
    }

    /*
     * 查询一个订单，只能查自己的订单
     */
    @GetMapping(path = "/api/orders/{id}")
    public ResponseEntity<Order> getOrderById(HttpServletRequest request, @PathVariable("id") Long id) {
        String username = jwtService.getUsername(request);
        if (null == username) {
            return new ResponseEntity<>(HttpStatus.FORBIDDEN);
        }
        User user = userService.findUserByUsername(username);
        if (null == user) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        Order order = orderService.getOrderById(id);
        if (null == order) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        if (order.getUserId().equals(user.getId())) {
            return new ResponseEntity<>(HttpStatus.FORBIDDEN);
        } else {
            return new ResponseEntity<>(order, HttpStatus.OK);
        }
    }

    /*
     * 修改一个订单，但是订单一般不允许修改，修改之前需要判断订单是不是自己的
     */
    @PutMapping(path = "/api/orders/{id}")
    public ResponseEntity<Order> updateOrder(HttpServletRequest request, @PathVariable("id") Long id, @RequestBody Order order) {
        String username = jwtService.getUsername(request);
        if (null == username) {
            return new ResponseEntity<>(HttpStatus.FORBIDDEN);
        }
        User user = userService.findUserByUsername(username);
        if (null == user) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        Order oldOrder = orderService.getOrderById(id);
        if (null == oldOrder) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        if (!oldOrder.getUserId().equals(user.getId())) {
            return new ResponseEntity<>(HttpStatus.FORBIDDEN);
        }
        int row = orderService.updateOrder(order);
        if (row == 0) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        } else {
            return new ResponseEntity<>(order, HttpStatus.OK);
        }
    }

    /*
     * 删除一个订单，必须是自己的才能删除
     */
    @DeleteMapping(path = "/api/orders/{id}")
    public ResponseEntity<Order> deleteOrderById(HttpServletRequest request, @PathVariable("id") Long id) {
        String username = jwtService.getUsername(request);
        if (null == username) {
            return new ResponseEntity<>(HttpStatus.FORBIDDEN);
        }
        User user = userService.findUserByUsername(username);
        if (null == user) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        Order oldOrder = orderService.getOrderById(id);
        if (null == oldOrder) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        if (oldOrder.getUserId() != user.getId()) {
            return new ResponseEntity<>(HttpStatus.FORBIDDEN);
        }
        int row = orderService.deleteOrderById(id);
        if (row == 0) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        } else {
            return new ResponseEntity<>(oldOrder, HttpStatus.NO_CONTENT);
        }
    }

    /*
     * 查询订单列表，只能查自己的订单
     */
    @GetMapping(path = "/api/orders")
    public ResponseEntity<List<Order>> getOrdersByUserId(HttpServletRequest request, @RequestParam("pageNo") Integer pageNo, @RequestParam("pageNum") Integer pageNum) {
        String username = jwtService.getUsername(request);
        if (null == username) {
            return new ResponseEntity<>(HttpStatus.FORBIDDEN);
        }
        User user = userService.findUserByUsername(username);
        if (null == user) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        Page<Order> page = new Page<>(pageNo, pageNum);
        IPage<Order> result = orderService.getOrdersByUserId(page, user.getId());
        List<Order> orders = result.getRecords();
        return new ResponseEntity<>(orders, HttpStatus.OK);
    }
}
